<?php
// +----------------------------------------------------------------------
// | Description: 客户模块设置
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com 
// +----------------------------------------------------------------------

namespace addons\qingdong\controller;

use addons\qingdong\model\Customer;
use addons\qingdong\model\Staff;

/**
 * 客户模块设置
 */
class Setting extends StaffApi
{


    /**
     * 获取团队成员
     */
    public function team()
    {
        $id = input('id');
        $customer = Customer::get($id);
        if (empty($customer)) {
            $this->error('客户不存在');
        }
        $owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
        $rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
        $ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();

        $staffs = [];
        if ($owner_staff) {
            $staffs[] = [
                'id' => $owner_staff->id,
                'name' => $owner_staff->name,
                'img' => $owner_staff->img,
                'post' => $owner_staff->post,
                'mobile' => $owner_staff->mobile,
                'roles' => 1,
                'is_edit' => 1,
            ];
        }
        foreach ($rw_staffs as $v) {
            $staffs[] = [
                'id' => $v->id,
                'name' => $v->name,
                'img' => $v->img,
                'post' => $v->post,
                'mobile' => $v->mobile,
                'roles' => 2,
                'is_edit' => 1,
            ];
        }
        foreach ($ro_staffs as $v) {
            $staffs[] = [
                'id' => $v->id,
                'name' => $v->name,
                'img' => $v->img,
                'post' => $v->post,
                'mobile' => $v->mobile,
                'roles' => 2,
                'is_edit' => 0,
            ];
        }

        $this->success('请求成功', $staffs);
    }

    /**
     * 修改团队成员
     */
    public function editShowStaff()
    {
        $id = input('id');
        $staff = input('staff/a');
        $model = Customer::get($id);
        if (empty($model)) {
            $this->error('客户不存在');
        }
        $ro_staff_id = [];
        $rw_staff_id = [];
        foreach ($staff as $v) {
            if ($v['is_edit'] == 1) {
                $rw_staff_id[] = $v['id'];
            } else {
                $ro_staff_id[] = $v['id'];
            }
        }
        $ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
        $rw_staff_id=implode(',', $rw_staff_id);
        $ro_staff_id=implode(',', $ro_staff_id);
        $result = $model->save(['rw_staff_id' => ",{$rw_staff_id},",
            'ro_staff_id' => ",{$ro_staff_id},"]);
        if ($result === false) {
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }

}